#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <sys/select.h>

#include "Socket.h"
#include "Log.h"

using namespace LogMudule;
using namespace sockedmodule;

#define NUM sizeof(fd_set) * 8
using std::cout;
using std::endl;

const int gdefaultfd = -1;

class SelectServer
{
public:
    SelectServer(int port)
        : _port(port), _listen_sockfd(std::make_unique<TcpSocket>()), _isrunning(false)
    {
    }
    void Init()
    {
        _listen_sockfd->BuildTcpSocketMethod(_port);
        for (int i = 0; i < NUM; i++)
        {
            _fd_array[i] = gdefaultfd;
        }
        _fd_array[0] = _listen_sockfd->Fd();
    }
    void Start()
    {
        fd_set reds;
        _isrunning = true;

        while (_isrunning)
        {
            FD_ZERO(&reds);
            struct timeval timeous = {10, 0};
            int maxfd = gdefaultfd;
            for (int i = 0; i < NUM; i++)
            {
                if (_fd_array[i] == gdefaultfd)
                {
                    continue;
                }
                FD_SET(_fd_array[i], &reds);

                if (_fd_array[i] > maxfd)
                {
                    maxfd = _fd_array[i];
                }
            }
            int n = select(maxfd + 1, &reds, nullptr, nullptr, &timeous);
            switch (n)
            {
            case 0:
                std::cout << "time out" << std::endl;
                break;
            case -1:
                std::cerr << "select" << endl;
                break;
            default:
                cout << "有事件就绪了 timeous:" << timeous.tv_sec << ":" << timeous.tv_usec << endl;
                Dispatcher(reds);
                break;
            }
        }
        _isrunning = false;
    }
    void Recver(int i)
    {
        char buffer[1024];
        int n = recv(_fd_array[i], buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "client#" << buffer << endl;
            std::string message = "echo#";
            message += buffer;
            send(_fd_array[i], message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::ERROR) << "客户端退出" << _fd_array[i];
            close(_fd_array[i]);
            _fd_array[i] = gdefaultfd;
        }
        else
        {
            LOG(LogLevel::ERROR) << "revc error" << _fd_array[i];
            close(_fd_array[i]);
            _fd_array[i] = gdefaultfd;
        }
    }
    void Accepter()
    {
        IntAddr client;
        int newsockfd = _listen_sockfd->Accepter(&client);
        if (newsockfd < 0)
        {
            return;
        }
        else
        {
            cout << "客户端获得了一个新的链接 sockfd:" << newsockfd << "client:" << client.Addr() << endl;
            int pos = gdefaultfd;
            for (int i = 0; i < NUM; i++)
            {
                if (_fd_array[i] == gdefaultfd)
                {
                    pos = i;
                    break;
                }
            }
            if (pos == -1)
            {
                LOG(LogLevel::ERROR) << "服务器已经满了";
                close(newsockfd);
            }
            else
            {
                _fd_array[pos] = newsockfd;
            }
        }
    }
    void Dispatcher(fd_set &reds)
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fd_array[i] == gdefaultfd)
            {
                continue;
            }
            if (_fd_array[i] == _listen_sockfd->Fd())
            {
                if (FD_ISSET(_fd_array[i], &reds))
                {
                    Accepter();
                }
            }
            else
            {
                if (FD_ISSET(_fd_array[i], &reds))
                {
                    Recver(i);
                }
            }
        }
    }
    ~SelectServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_sockfd;
    bool _isrunning;
    int _fd_array[NUM];
};